package com.tulele.vtool.task.async;

import com.alibaba.fastjson.JSONObject;
import com.tulele.vtool.bus.model.UserInfo;
import com.tulele.vtool.bus.model.thirdparty.WxNotifyMsgSetInfo;
import com.tulele.vtool.bus.model.thirdparty.WxPushUserInfo;
import com.tulele.vtool.bus.service.IArticleService;
import com.tulele.vtool.bus.service.IUserService;
import com.tulele.vtool.bus.service.SysGzhService;
import com.tulele.vtool.util.DateUtil;
import com.tulele.vtool.util.RedisCacheUtil;
import com.tulele.vtool.util.SysConstant;
import com.tulele.vtool.util.ToolUtil;
import com.tulele.vtool.wechat.service.WeixinService;
import com.tulele.vtool.wechat.service.WeixinServiceDL;
import com.tulele.vtool.wechat.service.WeixinServiceMap;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;
import java.util.Set;

@Component
@Slf4j
public class VipDiscountActivityPushAsyncTask {

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Autowired
    private ObjectFactory<WeixinServiceDL> objectFactory;

    @Autowired
    private SysGzhService sysGzhService;

    @Autowired
    private IUserService userService;

    //20200512 调整参数，多线程跑
    @Async("taskExecutor")
    public void execute(String redisKey, String profile) throws Exception {

//        log.info("[enter VipDiscountActivityPushAsyncTask] = " + redisKey);

        Object pushUserJsonObject = redisCacheUtil.getCacheObject(redisKey);
        if (pushUserJsonObject != null) {

            String pushUserJson = (String) pushUserJsonObject;
            log.info("[pushUserJson] = " + pushUserJson);

            WxPushUserInfo wxPushUserInfo = JSONObject.parseObject(pushUserJson, WxPushUserInfo.class);

            if (wxPushUserInfo != null) {

                //UserInfo userInfo = userService.getUserSubPnInfo(wxPushUserInfo.getUserId());//20200422

                UserInfo userInfo = userService.getUserCreateTime(wxPushUserInfo.getUserId());

                if (userInfo != null) {

                    Date subscriberTime = userInfo.getCreateTime();

                    if (subscriberTime != null) {

                        int couponRemainTime = 0;

                        int vipStatus = Optional.ofNullable(userInfo.getVipStatus()).orElse(0);

                        if (subscriberTime != null && vipStatus == 0) {

                            //优惠券剩余有效时间
                            couponRemainTime = SysConstant.COUPON_VALID_TIME - DateUtil.getTimeDiff(3, subscriberTime);
                            if (couponRemainTime < 0 || couponRemainTime > 26) {
                                couponRemainTime = 0;
                            }

                            log.info("[userId] = " + userInfo.getUserId() + "[couponRemainTime] = " + couponRemainTime);

                            //优惠券过期前2两小时发送推送
                            if (couponRemainTime == 1 || couponRemainTime == 2) {

                                Object couponRemindStatus = redisCacheUtil.getCacheObject(userInfo.getUserId() + "couponRemindStatus");
                                if (couponRemindStatus == null) {

                                    String kefuMsg = userService.generateVipDiscountExpirePushMsg(couponRemainTime,profile);
                                    if(userInfo.getPhoneModel().equals(SysConstant.IOS)){
                                        kefuMsg = ToolUtil.handleMsgmenuidByIOS(kefuMsg);
                                    }
                                    WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(wxPushUserInfo.getOpenId()).content(kefuMsg).build();
                                    try {
                                        WeixinServiceDL weixinService= WeixinServiceMap.getWeixinService(profile);
                                        if(weixinService==null) {
                                            weixinService = objectFactory.getObject();
                                            weixinService.reSetConfigStorage(profile);
                                            WeixinServiceMap.putWeixinService(profile,weixinService);
                                        }
                                        weixinService.getKefuService().sendKefuMessage(message);
                                        redisCacheUtil.setCacheObject(userInfo.getUserId() + "couponRemindStatus", 1, 10800);
                                    } catch (WxErrorException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
